﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Infrastructure
{
    public class GlobalExceptionFilter : Attribute, IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            var httpContext = context.HttpContext;
            var request = httpContext.Request;

            // 获取请求路径
            var path = request.Path;

            // 获取业务标识（可根据实际情况调整，比如Header、路由、接口名等）
            var business = request.Headers.ContainsKey("Business-Name")
                ? request.Headers["Business-Name"].ToString()
                : context.ActionDescriptor.DisplayName;

            // 获取异常信息
            var exceptionMessage = context.Exception.Message;
            var exceptionStackTrace = context.Exception.StackTrace;

            // 记录日志
            _logger.LogError(context.Exception,
                "全局异常捕获：路径：{Path}，业务：{Business}，错误信息：{Message}",
                path, business, exceptionMessage);

            // 返回统一错误响应
            context.Result = new ObjectResult(new
            {
                Code = 500,
                Message = "服务器内部错误",
                Path = path,
                Business = business,
                Error = exceptionMessage
            })
            {
                StatusCode = 500
            };

            context.ExceptionHandled = true;
        }
    }
}
